package com.carleasoft.mps.cms.business.write.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.cms.business.article.bean.vo.SlideshowEIPVo;
import com.carleasoft.mps.cms.business.article.constants.ExceptionCMSEnum;
import com.carleasoft.mps.cms.business.clerk.bean.DealProcessEntity;
import com.carleasoft.mps.cms.business.leave.bean.entity.ReportEntity;
import com.carleasoft.mps.cms.business.personal.bean.entity.PersonalCenterEntity;
import com.carleasoft.mps.cms.business.personal.service.PersonalCenterService;
import com.carleasoft.mps.cms.business.resource.bean.vo.WebCountVo;
import com.carleasoft.mps.cms.business.user.bean.UserSkill;
import com.carleasoft.mps.cms.business.user.service.UserSkillService;
import com.carleasoft.mps.cms.business.write.bean.entity.LeadingCadreEntity;
import com.carleasoft.mps.cms.business.write.bean.entity.LeadingViewEntity;
import com.carleasoft.mps.cms.business.write.bean.po.LeadingCadrePagePo;
import com.carleasoft.mps.cms.business.write.bean.vo.LeadingCountVo;
import com.carleasoft.mps.cms.business.write.bean.vo.UpAndDownVo;
import com.carleasoft.mps.cms.business.write.dao.LeadingCadreMapper;
import com.carleasoft.mps.cms.business.write.service.LeadingCadreService;
import com.carleasoft.mps.cms.business.write.service.LeadingViewService;
import com.carleasoft.mps.core.exceptions.BusinessException;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.core.utils.IBeanUtil;
import com.carleasoft.mps.core.utils.IpUtils;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.ibatis.annotations.Case;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: yangHao
 * @createDate:2023/6/7
 * @description:
 */
@Service
public class LeadingCadreServiceImpl extends ServiceImpl<LeadingCadreMapper, LeadingCadreEntity> implements LeadingCadreService {

    @Autowired
    private LeadingViewService leadingViewService;
    @Autowired
    private PersonalCenterService personalCenterService;
    @Autowired
    private LeadingCadreService leadingCadreService;
    @Autowired
    private UserSkillService userSkillService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveLeading(LeadingCadreEntity leadingCadreEntity, HttpServletRequest request) {
        IBeanUtil.paramVerify(leadingCadreEntity,"type");
        leadingCadreEntity.setWriteCode(IdWorker.getIdStr());
        leadingCadreEntity.setCreateTime(LocalDateTime.now());
        leadingCadreEntity.setCreationDate(LocalDate.now());
        leadingCadreEntity.setIsDelete(0);
        if (leadingCadreEntity.getType() == 2) {
            UserSkill userSkillServiceOne = userSkillService.getOne(Wrappers.<UserSkill>lambdaQuery()
                    .eq(UserSkill::getDeptCode, leadingCadreEntity.getDeptCode()));
            leadingCadreEntity.setUserCode(userSkillServiceOne.getUserCode());
            String userName = this.getBaseMapper().userInfo(userSkillServiceOne.getUserCode());
            leadingCadreEntity.setUserName(userName);
        }
        String ipAddr = IpUtils.getIpAddr(request);
        leadingCadreEntity.setIpAddress(ipAddr);
        PersonalCenterEntity personalCenterEntity = new PersonalCenterEntity();
        if (leadingCadreEntity.getIntention() != null) {
            Integer intention = leadingCadreEntity.getIntention();
            String aaa = null;
            switch (intention) {
                case 1:
                    aaa = "咨询信件";
                    break;
                case 2:
                    aaa = "求助信件";
                    break;
                case 3:
                    aaa = "意见建议信件";
                    break;
                case 4:
                    aaa = "投诉举报信件";
                    break;
                case 5:
                    aaa = "表扬信件";
                    break;
            }
            personalCenterEntity.setMessage("您收到一条" + aaa + " 进入系统");

        }
        personalCenterEntity.setResourceType(1);
        personalCenterEntity.setType(3);
        personalCenterEntity.setUserCode(leadingCadreEntity.getUserCode());
        personalCenterService.savePersonalCenter(personalCenterEntity);
        return this.save(leadingCadreEntity);
    }

    @Override
    public Page<LeadingCadreEntity> pageQuery(Page page, LeadingCadrePagePo leadingCadrePagePo) {

        Page<LeadingCadreEntity> leadingCadreEntityPage = this.getBaseMapper().pageQuery(page,leadingCadrePagePo);
        if (CollUtil.isNotEmpty(leadingCadreEntityPage.getRecords())) {
            List<String> writeCodes = leadingCadreEntityPage.getRecords().stream().map(LeadingCadreEntity::getWriteCode).collect(Collectors.toList());
            List<LeadingViewEntity> leadingViewEntities = leadingViewService.list(Wrappers.<LeadingViewEntity>lambdaQuery()
                    .in(LeadingViewEntity::getWriteCode, writeCodes));
            if (CollUtil.isNotEmpty(leadingViewEntities)) {
                Map<String, List<LeadingViewEntity>> map = leadingViewEntities.stream().collect(Collectors.groupingBy(LeadingViewEntity::getWriteCode));
                for (LeadingCadreEntity record : leadingCadreEntityPage.getRecords()) {
                    if (map.containsKey(record.getWriteCode())) {
                        List<LeadingViewEntity> viewEntities = map.get(record.getWriteCode());
                        int sum = viewEntities.stream().mapToInt(LeadingViewEntity::getViewOne).sum();
                        record.setView(sum);
                    }
                }
            }

        }
        return leadingCadreEntityPage;
    }

    @Override
    public LeadingCadreEntity detail(LeadingCadrePagePo leadingCadrePagePo) {
        LeadingCadreEntity leadingCadreEntity = this.getOne(Wrappers.<LeadingCadreEntity>lambdaQuery()
                .eq(LeadingCadreEntity::getWriteCode, leadingCadrePagePo.getWriteCode())
        .eq(LeadingCadreEntity::getIsDelete,0));

//        if (leadingCadreEntity.getIsOpen().equals(3) && !leadingCadrePagePo.getPassword().equals(leadingCadreEntity.getSecretKey())) {
//            throw new BusinessException(ExceptionCMSEnum.PASS_WORD);
//        }
        return leadingCadreEntity;
    }

    @Override
    public LeadingCountVo leadingCount() {
        LeadingCountVo leadingCountVo = new LeadingCountVo();
        List<LeadingCadreEntity> leadingCadreEntities = this.list(Wrappers.<LeadingCadreEntity>lambdaQuery()
        .eq(LeadingCadreEntity::getIsDelete,0));
        if (CollUtil.isNotEmpty(leadingCadreEntities)) {
            leadingCountVo.setConsult(leadingCadreEntities.size());
            List<LeadingViewEntity> leadingViewEntities = leadingViewService.list();
            if (CollUtil.isNotEmpty(leadingViewEntities)) {
                // 总访问量
                leadingCountVo.setView(leadingViewEntities.size());
            }
            Map<LocalDate, List<LeadingViewEntity>> map = leadingViewEntities.stream().collect(Collectors.groupingBy(LeadingViewEntity::getViewDate));
            if (map.containsKey(LocalDate.now())) {
                List<LeadingViewEntity> viewEntities = map.get(LocalDate.now());
                int sum = viewEntities.stream().mapToInt(LeadingViewEntity::getViewOne).sum();
                leadingCountVo.setToday(sum);
            }
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DATE, -1);
            Date d = cal.getTime();
            SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
            String ZUOTIAN = sp.format(d);//获取昨天日期
            LocalDate beginDateTime = LocalDate.parse(ZUOTIAN, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            if (map.containsKey(beginDateTime)) {
                List<LeadingViewEntity> viewEntities = map.get(beginDateTime);
                int sum = viewEntities.stream().mapToInt(LeadingViewEntity::getViewOne).sum();
                leadingCountVo.setYesterday(sum);
            }
            Map<LocalDate, List<LeadingCadreEntity>> listMap = leadingCadreEntities.stream().collect(Collectors.groupingBy(LeadingCadreEntity::getCreationDate));
            if (listMap.containsKey(LocalDate.now())) {
                List<LeadingCadreEntity> viewEntities = listMap.get(LocalDate.now());
                Set<String> collect = viewEntities.stream().map(LeadingCadreEntity::getIpAddress).collect(Collectors.toSet());
                leadingCountVo.setTodayIp(collect.size());
            }
            if (listMap.containsKey(beginDateTime)) {
                List<LeadingCadreEntity> viewEntities = listMap.get(beginDateTime);
                Set<String> collect = viewEntities.stream().map(LeadingCadreEntity::getIpAddress).collect(Collectors.toSet());
                leadingCountVo.setYesterdayIp(collect.size());
            }
        }
        // todo 还差 未回咨询 和已回咨询
        return leadingCountVo;
    }

    @Override
    public UpAndDownVo upAndDown(String writeCode) {
        UpAndDownVo upAndDownVo = new UpAndDownVo();
        List<LeadingCadreEntity> leadingCadreEntities = this.list(Wrappers.<LeadingCadreEntity>lambdaQuery()
                .eq(LeadingCadreEntity::getIsDelete,0)
                .orderByAsc(LeadingCadreEntity::getCreateTime));
        List<String> articleCodes = leadingCadreEntities.stream().map(LeadingCadreEntity::getWriteCode).collect(Collectors.toList());
        int last = articleCodes.size();
        int index = articleCodes.indexOf(writeCode);
        if (index == 0) {
            upAndDownVo.setUpCode(null);
            if (index == last - 1) {
                upAndDownVo.setDownCode(null);
            } else {
                String s = articleCodes.get(index + 1);
                LeadingCadreEntity one = this.getOne(Wrappers.<LeadingCadreEntity>lambdaQuery()
                        .eq(LeadingCadreEntity::getWriteCode, s));
                upAndDownVo.setDownCode(one);
            }
        } else {
            String s = articleCodes.get(index - 1);
            LeadingCadreEntity one = this.getOne(Wrappers.<LeadingCadreEntity>lambdaQuery()
                    .eq(LeadingCadreEntity::getWriteCode, s));
            upAndDownVo.setUpCode(one);
            if (index == last - 1) {
                upAndDownVo.setDownCode(null);
            } else {
                String s1 = articleCodes.get(index + 1);
                LeadingCadreEntity leadingCadreEntity = this.getOne(Wrappers.<LeadingCadreEntity>lambdaQuery()
                        .eq(LeadingCadreEntity::getWriteCode, s1));
                upAndDownVo.setDownCode(leadingCadreEntity);
            }
        }

        return upAndDownVo;
    }

    @Override
    public Page<LeadingCadreEntity> pageQueryWeb(Page page, LeadingCadrePagePo leadingCadrePagePo) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        leadingCadrePagePo.setUserCode(user.getUserCode());
        Page<LeadingCadreEntity> leadingCadreEntityPage = this.getBaseMapper().pageQueryWeb(page, leadingCadrePagePo);
        return leadingCadreEntityPage;
    }

    @Override
    public List<WebCountVo> leadingWebCount() {
//        1-咨询 2-求助 3-意见建议 4-投诉举报 5-表扬
        List<WebCountVo> webCountVos = new ArrayList<>();
        List<LeadingCadreEntity> leadingCadreEntities = this.list(Wrappers.<LeadingCadreEntity>lambdaQuery()
        .eq(LeadingCadreEntity::getIsDelete,0));
        if (CollUtil.isNotEmpty(leadingCadreEntities)) {
            Map<Integer, List<LeadingCadreEntity>> map = leadingCadreEntities.stream().collect(Collectors.groupingBy(LeadingCadreEntity::getIntention));
            WebCountVo webCountVo = new WebCountVo();
            webCountVo.setName("咨询");
            if (map.containsKey(1)) {
                webCountVo.setSum(map.get(1).size());
            }
            webCountVos.add(webCountVo);

            WebCountVo webCountVo1 = new WebCountVo();
            webCountVo1.setName("求助");
            if (map.containsKey(2)) {
                webCountVo1.setSum(map.get(2).size());
            }
            webCountVos.add(webCountVo1);

            WebCountVo webCountVo3 = new WebCountVo();
            webCountVo3.setName("意见建议");
            if (map.containsKey(3)) {
                webCountVo3.setSum(map.get(3).size());
            }
            webCountVos.add(webCountVo3);

            WebCountVo webCountVo4 = new WebCountVo();
            webCountVo4.setName("投诉举报");
            if (map.containsKey(4)) {
                webCountVo4.setSum(map.get(4).size());
            }
            webCountVos.add(webCountVo4);

            WebCountVo webCountVo5 = new WebCountVo();
            webCountVo5.setName("表扬");
            if (map.containsKey(5)) {
                webCountVo5.setSum(map.get(5).size());
            }
            webCountVos.add(webCountVo5);
        }
        return webCountVos;
    }

    @Override
    public boolean delete(String writeCode) {
        return this.update(Wrappers.<LeadingCadreEntity>lambdaUpdate()
        .eq(LeadingCadreEntity::getWriteCode,writeCode)
        .set(LeadingCadreEntity::getIsDelete,1));
    }
}
